package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.constant.YMConstantData;
import com.dwxt.cdms.dao.yumeng.*;
import com.dwxt.cdms.entity.ElectronicFence;
import com.dwxt.cdms.entity.EquipmentCustom;
import com.dwxt.cdms.util.UtilDao.Point;
import com.dwxt.cdms.view.*;
import com.dwxt.cdms.vo.YMData;
import com.dwxt.cdms.entity.yumeng.*;
import com.dwxt.cdms.util.DateUtil;
import com.dwxt.cdms.util.JsonUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 翎盟 service
 *
 * @author Kuang.JiaZhuo
 * @date 2020-09-08 11:59
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class YuMengService {

    private final BpDataMapper bpDataMapper;
    private final BtDataMapper btDataMapper;
    private final ExdeviceDataMapper exdeviceDataMapper;
    private final HrDataMapper hrDataMapper;
    private final LocDataMapper locDataMapper;
    private final LogDataMapper logDataMapper;
    private final LogRelationMapper logRelationMapper;
    private final ReceiveDataMapper receiveDataMapper;
    private final SleepAnalysisDataMapper sleepAnalysisDataMapper;
    private final SleepAnalysisResultMapper sleepAnalysisResultMapper;
    private final SleepAnalysisStatisticsMapper sleepAnalysisStatisticsMapper;
    private final SleepAnalysisTimeSlotMapper sleepAnalysisTimeSlotMapper;
    private final SleepDataMapper sleepDataMapper;
    private final StepDataMapper stepDataMapper;
    private final UserDataMapper userDataMapper;
    private final EquipmentCustomService equipmentCustomService;
    private final HealthService healthService;
    private final WarningService warningService;
    private final ElectronicFenceService electronicFenceService;

    // 被转发的 serverName
    @Value("${watch.forwarded}")
    private String forwarded;

    // 转发的目标url
    @Value("${watch.targetUrl}")
    private String targetUrl;


    /**
     * @方法名：request2YMData
     * @描述： 传入request返回YMData
     * @作者： kjz
     * @日期： Created in 2020/9/9 18:24
     */
    public YMData request2YMData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String line = null;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String bodyStr = sb.toString();
        JSONObject resultStr = (JSONObject) JSONObject.parse(bodyStr);
        /** 转发Request */
        forwardRequest(request.getServerName(), resultStr);
        String data = resultStr.getString("Data");
        String type = resultStr.getString("Type");
        long distributionTime = resultStr.getLongValue("DistributionTime");
        YMData ymData = new YMData()
                .setDataString(bodyStr)
                .setData(data)
                .setType(type)
                .setDistributionTime(distributionTime);
        return ymData;
    }

    /**
     * @方法名：forwardRequest
     * @描述： 厂家只提供一个推送的url, 要同步两个数据库，就自己转发请求
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2020/9/17 0:38
     */
    public BaseResult forwardRequest(String serverName, JSONObject resultStr) {
        if (serverName.equals(forwarded)) {
            RestTemplate restTemplate = new RestTemplate();
            BaseResult baseResult = restTemplate.postForObject(targetUrl, resultStr, BaseResult.class);
            return baseResult;
        }
        return null;
    }

    /**
     * @方法名：receiveData
     * @描述： 翎盟 健康数据
     * @作者： kjz
     * @日期： Created in 2020/9/8 14:06
     */
    @Transactional(rollbackFor = Exception.class)
    public Object receiveData(HttpServletRequest request) {

        YMData ymData = request2YMData(request);

        /** 保存接收记录*/
        String receiveId = SnowIdUtil.getInstance().nextId();
        ReceiveData receiveData = new ReceiveData()
                .setId(receiveId)
                .setCreateTime(LocalDateTime.now())
                .setType(ymData.getType().trim())
                .setReceiveData(ymData.getDataString());

        int result = receiveDataMapper.insert(receiveData);

        //数据类型
        String Type = ymData.getType();

        System.err.println(ymData);

        String data = ymData.getData();

        //如果是对象，改成数据
        if (JsonUtil.judgeJsonObjectOrArray(data).equals(VariableConstants.STRING_CONSTANT_1)) {
            data = "[" + data + "]";
        }


        //睡眠数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_1)) {
            List<SleepData> sleepDataList = JSON.parseArray(data, SleepData.class);
            insertSleepData(sleepDataList, receiveId);
        }

        //计步数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_2)) {
            List<StepData> stepDataList = JSON.parseArray(data, StepData.class);
            insertStepData(stepDataList, receiveId);
        }

        //心率数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_3)) {
            List<HrData> hrDataList = JSON.parseArray(data, HrData.class);
            insertHrData(hrDataList, receiveId);

        }

        //血压数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_4)) {
            List<BpData> bpDataList = JSON.parseArray(data, BpData.class);
            insertBpData(bpDataList, receiveId);
        }

        //体温数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_5)) {
            List<BtData> btDataList = JSON.parseArray(data, BtData.class);
            insertBtData(btDataList, receiveId);
        }

        //定位数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_6)) {
            List<LocData> locDataList = JSON.parseArray(data, LocData.class);
            insertLocData(locDataList, receiveId);
        }

        //用户信息
        if (Type.trim().equals(YMConstantData.DATA_TYPE_7)) {
            System.err.println(data);
            List<UserData> userDataList = JSON.parseArray(data, UserData.class);
            insertUserData(userDataList, receiveId);
        }

        //设备日志
        if (Type.trim().equals(YMConstantData.DATA_TYPE_8)) {
            List<LogData> logDataList = JSON.parseArray(data, LogData.class);
//            System.err.println(JSON.toJSON(logDataList));
            insertLogData(logDataList, receiveId);
        }

        //外接设备数据
        if (Type.trim().equals(YMConstantData.DATA_TYPE_9)) {
            List<ExdeviceData> exdeviceDataList = JSON.parseArray(data, ExdeviceData.class);
            insertExdeviceData(exdeviceDataList, receiveId);
        }

        //睡眠分析
        if (Type.trim().equals(YMConstantData.DATA_TYPE_10)) {
            System.err.println(data);
            List<SleepAnalysisData> sleepAnalysisDataList = JSON.parseArray(data, SleepAnalysisData.class);
//            System.err.println("-------------睡眠分析数据-------------");
//            System.err.println(JSON.toJSON(sleepAnalysisDataList));
            insertSleepAnalysisData(sleepAnalysisDataList, receiveId);
        }
        return result;
    }


    /**
     * @方法名：insertSleepAnalysisData
     * @描述： 新增 睡眠分析
     * @作者： kjz
     * @日期： Created in 2020/9/9 19:39
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertSleepAnalysisData(List<SleepAnalysisData> sleepAnalysisDataList, String receiveId) {
        int result = 0;
        String sleepAnalysisId = SnowIdUtil.getInstance().nextId();
        for (SleepAnalysisData sleepAnalysisData : sleepAnalysisDataList) {
            sleepAnalysisData.setReceiveDataId(receiveId).setId(sleepAnalysisId)
                    .setDayTime(DateUtil.timeStrStamp2DateStr(sleepAnalysisData.getDayTime()))
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);

            int count = sleepAnalysisDataMapper.countSleepAnalysisDataByDevAndTimeAndUserId(sleepAnalysisData);
            if (count == 0) {
                /**
                 * 睡眠分时段数据
                 */
                SleepDataView sleepData = sleepAnalysisData.getSleepData();
                NphaseStamp nphaseStamp = sleepData.getNphaseStamp();
                List<N2Data> N2 = nphaseStamp.getN2();


                //加入客户id
                String deviceIdentity = sleepAnalysisData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    sleepAnalysisData.setCustomerId(equipmentCustom.getCustomerId());

                    for (N2Data n2Data : N2) {
                        //浅睡分期时间片段
                        SleepAnalysisTimeSlot sleepAnalysisTimeSlot = new SleepAnalysisTimeSlot()
                                .setId(SnowIdUtil.getInstance().nextId())
                                .setSleepAnalysisId(sleepAnalysisId)
                                .setCreateTime(LocalDateTime.now())
                                .setTimeSlotType(VariableConstants.STRING_CONSTANT_1)
                                .setStart(DateUtil.timeStrStamp2TimeStr(n2Data.getStart()))
                                .setEnd(DateUtil.timeStrStamp2TimeStr(n2Data.getEnd()))
                                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                        sleepAnalysisTimeSlotMapper.insert(sleepAnalysisTimeSlot);
                    }

                    List<N3Data> N3 = nphaseStamp.getN3();
                    for (N3Data n3Data : N3) {
                        //深睡分期时间片段
                        SleepAnalysisTimeSlot sleepAnalysisTimeSlot = new SleepAnalysisTimeSlot()
                                .setId(SnowIdUtil.getInstance().nextId())
                                .setSleepAnalysisId(sleepAnalysisId)
                                .setCreateTime(LocalDateTime.now())
                                .setTimeSlotType(VariableConstants.STRING_CONSTANT_2)
                                .setStart(DateUtil.timeStrStamp2TimeStr(n3Data.getStart()))
                                .setEnd(DateUtil.timeStrStamp2TimeStr(n3Data.getEnd()))
                                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                        sleepAnalysisTimeSlotMapper.insert(sleepAnalysisTimeSlot);
                    }

                    List<RphaseStampData> RphaseStamp = sleepData.getRphaseStamp();
                    for (RphaseStampData rphaseStamp : RphaseStamp) {
                        //REM(快速眼动)分期时间片段
                        SleepAnalysisTimeSlot sleepAnalysisTimeSlot = new SleepAnalysisTimeSlot()
                                .setId(SnowIdUtil.getInstance().nextId())
                                .setSleepAnalysisId(sleepAnalysisId)
                                .setCreateTime(LocalDateTime.now())
                                .setTimeSlotType(VariableConstants.STRING_CONSTANT_3)
                                .setStart(DateUtil.timeStrStamp2TimeStr(rphaseStamp.getStart()))
                                .setEnd(DateUtil.timeStrStamp2TimeStr(rphaseStamp.getEnd()))
                                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                        sleepAnalysisTimeSlotMapper.insert(sleepAnalysisTimeSlot);
                    }

                    List<WphaseStampData> WphaseStamp = sleepData.getWphaseStamp();
                    for (WphaseStampData wphaseStamp : WphaseStamp) {
                        //清醒分期时间片段
                        SleepAnalysisTimeSlot sleepAnalysisTimeSlot = new SleepAnalysisTimeSlot()
                                .setId(SnowIdUtil.getInstance().nextId())
                                .setSleepAnalysisId(sleepAnalysisId)
                                .setCreateTime(LocalDateTime.now())
                                .setTimeSlotType(VariableConstants.STRING_CONSTANT_4)
                                .setStart(DateUtil.timeStrStamp2TimeStr(wphaseStamp.getStart()))
                                .setEnd(DateUtil.timeStrStamp2TimeStr(wphaseStamp.getEnd()))
                                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                        sleepAnalysisTimeSlotMapper.insert(sleepAnalysisTimeSlot);
                    }

                    /**
                     * 睡眠分析结果
                     */
                    SleepAnalysis sleepAnalysis = sleepAnalysisData.getSleepAnalysis();
                    SleepAnalysisResult sleepAnalysisResult = new SleepAnalysisResult()
                            .setId(SnowIdUtil.getInstance().nextId())
                            .setCreateTime(LocalDateTime.now())
                            .setSleepAnalysisId(sleepAnalysisId)
                            .setSleepAssement(sleepAnalysis.getSleepAssement())
                            .setSleepSuggest(sleepAnalysis.getSleepSuggest())
                            .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                    sleepAnalysisResultMapper.insert(sleepAnalysisResult);

                    /**
                     * 睡眠统计
                     */
                    SleepStastic sleepStastic = sleepAnalysisData.getSleepStastic();
                    SleepAnalysisStatistics sleepAnalysisStatistics = new SleepAnalysisStatistics()
                            .setId(SnowIdUtil.getInstance().nextId())
                            .setSleepAnalysisId(sleepAnalysisId)
                            .setSleepStart(DateUtil.timeStrStamp2TimeStr(sleepStastic.getSleepStart()))
                            .setSleepEnd(DateUtil.timeStrStamp2TimeStr(sleepStastic.getSleepEnd()))
                            .setSleepDuration(sleepStastic.getSleepDuration())
                            .setN2PhaseDuration(sleepStastic.getN2PhaseDuration())
                            .setN3PhaseDuration(sleepStastic.getN3PhaseDuration())
                            .setRphaseDuration(sleepStastic.getRphaseDuration())
                            .setWphaseDuration(sleepStastic.getWphaseDuration())
                            .setCreateTime(LocalDateTime.now())
                            .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                    sleepAnalysisStatisticsMapper.insert(sleepAnalysisStatistics);

                    result += sleepAnalysisDataMapper.insert(sleepAnalysisData);
                }


            } else {
                System.err.println("----睡眠分析数据已经录入过-----");
                System.err.println(JSON.toJSON(sleepAnalysisData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertBpData
     * @描述： 新增血压数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:45
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertBpData(List<BpData> bpDataList, String receiveId) {
        int result = 0;
        for (BpData bpData : bpDataList) {
            bpData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(bpData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);

            int count = bpDataMapper.countBpDataByDevAndTime(bpData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = bpData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    bpData.setCustomerId(equipmentCustom.getCustomerId());
                    healthService.judgeIsNormalAndInsertRecord(bpData);
                    result += bpDataMapper.insert(bpData);
                }

            } else {
                System.err.println("----血压数据已经录入过-----");
                System.err.println(JSON.toJSON(bpData));
            }
        }
        return result;
    }

    /**
     * @方法名：insertBtData
     * @描述： 新增体温数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:44
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertBtData(List<BtData> btDataList, String receiveId) {
        int result = 0;
        for (BtData btData : btDataList) {
            btData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(btData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            int count = btDataMapper.countBtDataByDevAndTime(btData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = btData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    btData.setCustomerId(equipmentCustom.getCustomerId());
                    healthService.judgeIsNormalAndInsertRecord(btData);
                    result += btDataMapper.insert(btData);
                }

            } else {
                System.err.println("----体温数据已经录入过-----");
                System.err.println(JSON.toJSON(btData));
            }
        }
        return result;
    }

    /**
     * @方法名：insertLocData
     * @描述： 新增定位数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertLocData(List<LocData> locDataList, String receiveId) {
        int result = 0;
        for (LocData locData : locDataList) {
            locData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(locData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);

            int count = locDataMapper.countLocDataByDevAndTime(locData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = locData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    locData.setCustomerId(equipmentCustom.getCustomerId());
                    result += locDataMapper.insert(locData);
                    //电子围栏报警
                    ElectronicFence electronicFence = electronicFenceService.selectFenceByCustomerId(equipmentCustom.getCustomerId());
                    if (electronicFence != null && electronicFence.getStatus() == 1) {
                        Point point = new Point(Double.valueOf(locData.getLongitude()), Double.valueOf(locData.getLatitude()));
                        boolean warning = electronicFenceService.isWarning(point, equipmentCustom.getCustomerId());
                        if (warning) {
                            warningService.insertWarningElectronic(locData);
                        }
                    }
                }

            } else {
                System.err.println("----定位数据已经录入过-----");
                System.err.println(JSON.toJSON(locData));
            }
        }
        return result;
    }

    /**
     * @方法名：insertUserData
     * @描述： 新增用户信息
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertUserData(List<UserData> userDataList, String receiveId) {
        int result = 0;
        for (UserData userData : userDataList) {
            userData.setReceiveDataId(receiveId)
                    .setBirthDay(userData.getBirthDay())
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            int count = userDataMapper.countUserDataByUserId(userData);
            if (count == 0) {
                result += userDataMapper.insert(userData);
            } else {
                System.err.println("-----用户数据已经录入过-----");
                System.err.println(JSON.toJSON(userData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertLogData
     * @描述： 新增设备日志
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:42
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertLogData(List<LogData> logDataList, String receiveId) {
        int result = 0;
        for (LogData logData : logDataList) {
            String logId = SnowIdUtil.getInstance().nextId();
            logData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(logData.getTime()))
                    .setId(logId)
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);

            int count = logDataMapper.countLogDataDevAndTime(logData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = logData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    logData.setCustomerId(equipmentCustom.getCustomerId());

                    result += logDataMapper.insert(logData);

                    String logType = logData.getLogType();
                    if (VariableConstants.STRING_CONSTANT_0.equals(logType)) {
                        /** 新增sos报警信息 */
                        warningService.insertWarningBySos(logData);
                        SOSPoint sosPoint = logData.getSosPoint();
                        if (sosPoint != null) {
                            LogRelation logRelation = new LogRelation()
                                    .setLogId(logId)
                                    .setCreateTime(LocalDateTime.now())
                                    .setLatitude(sosPoint.getLatitude())
                                    .setLongitude(sosPoint.getLongitude())
                                    .setId((SnowIdUtil.getInstance().nextId()))
                                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                            logRelationMapper.insert(logRelation);
                        }
                    } else if (VariableConstants.STRING_CONSTANT_1.equals(logType)) {
                        FenceAlarmPoint fenceAlarmPoint = logData.getFenceAlarmPoint();
                        if (fenceAlarmPoint != null) {
                            LogRelation logRelation = new LogRelation()
                                    .setLogId(logId)
                                    .setCreateTime(LocalDateTime.now())
                                    .setLatitude(fenceAlarmPoint.getLatitude())
                                    .setLongitude(fenceAlarmPoint.getLongitude())
                                    .setId((SnowIdUtil.getInstance().nextId()))
                                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
                            logRelationMapper.insert(logRelation);
                        }
                    }


                }
            } else {
                System.err.println("-----设备日志数据已经录入过-----");
                System.err.println(JSON.toJSON(logData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertExdeviceData
     * @描述： 新增外接设备数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:42
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertExdeviceData(List<ExdeviceData> exdeviceDataList, String receiveId) {
        int result = 0;
        for (ExdeviceData exdeviceData : exdeviceDataList) {
            exdeviceData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(exdeviceData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            int count = exdeviceDataMapper.countExdeviceDataByDevAndTime(exdeviceData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = exdeviceData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    exdeviceData.setCustomerId(equipmentCustom.getCustomerId());
                    result += exdeviceDataMapper.insert(exdeviceData);
                }

            } else {
                System.err.println("-----外接设备数据已经录入过-----");
                System.err.println(JSON.toJSON(exdeviceData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertHrData
     * @描述： 新增心率数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:33
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertHrData(List<HrData> hrDataList, String receiveId) {
        int result = 0;
        for (HrData hrData : hrDataList) {
            hrData.setReceiveDataId(receiveId)
                    .setTime(DateUtil.timeStrStamp2TimeStr(hrData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            int count = hrDataMapper.countHrDataByDevAndTime(hrData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = hrData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    hrData.setCustomerId(equipmentCustom.getCustomerId());
                    healthService.judgeIsNormalAndInsertRecord(hrData);
                    result += hrDataMapper.insert(hrData);
                }

            } else {
                System.err.println("-----心率数据已经录入过-----");
                System.err.println(JSON.toJSON(hrData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertStepData
     * @描述： 新增计步数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 15:25
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertStepData(List<StepData> stepDataList, String receiveId) {
        int result = 0;
        for (StepData stepData : stepDataList) {
            stepData.setReceiveDataId(receiveId)
                    .setBeginTime(DateUtil.timeStrStamp2TimeStr(stepData.getBeginTime()))
                    .setEndTime(DateUtil.timeStrStamp2TimeStr(stepData.getEndTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);
            int count = stepDataMapper.countStepDataByCondition(stepData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = stepData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    stepData.setCustomerId(equipmentCustom.getCustomerId());
                    result += stepDataMapper.insert(stepData);
                }

            } else {
                System.err.println("-----计步数据已经录入过-----");
                System.err.println(JSON.toJSON(stepData));
            }

        }
        return result;
    }

    /**
     * @方法名：insertSleepData
     * @描述： 新增睡眠数据
     * @作者： kjz
     * @日期： Created in 2020/9/9 14:16
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertSleepData(List<SleepData> sleepDateList, String receiveId) {
        int result = 0;
        for (SleepData sleepData : sleepDateList) {
            sleepData.setReceiveDataId(receiveId)
                    .setBeginTime(DateUtil.timeStrStamp2TimeStr(sleepData.getBeginTime()))
                    .setEndTime(DateUtil.timeStrStamp2TimeStr(sleepData.getEndTime()))
                    .setTime(DateUtil.timeStrStamp2DateStr(sleepData.getTime()))
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0);

            int count = sleepDataMapper.countSleepDataByDevAndTime(sleepData);
            if (count == 0) {
                //加入客户id
                String deviceIdentity = sleepData.getDeviceIdentity();
                EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceIdentity);
                if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
                    sleepData.setCustomerId(equipmentCustom.getCustomerId());
                    result += sleepDataMapper.insert(sleepData);
                }

            } else {
                System.err.println("-----睡眠数据已经录入过-----");
                System.err.println(JSON.toJSON(sleepData));
            }

        }
        return result;
    }
}
